package com.prototype.ECE492;




import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class ECE492_PrototypeActivity extends MapActivity {
	//Variables
	String ACTNAME = "ECE492_PrototypeActivity";
	MapView mapView;	//Map handler
	LocationManager locationManager; //Location manager
	LocationListener locationListener; //location listener
	MapController mapControl;	//Map control
	MapItem mapItem;
	MyLocationOverlay myLocationOverlay;
	List<Overlay> mapOverlays;
	ArrayList<TagType> tagTypes = new ArrayList<TagType>();
//	OverlayItem overlayitem;
	GeoPoint currentLocationPoint;

	SharedPreferences menuSettings;
	SharedPreferences.Editor prefEditor;
//	int checkBoxState;
	TagType currentType;
	String TagFileName = "tagfile";
	@Override
	//Method is called on start-up of application
	
	public void onCreate(Bundle savedInstanceState) {
		//Auto-Generated
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		//Acquire a reference to system location manager
		locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		//Defines listener that responds to location updates
		locationListener = new myLocationListener();
		//Register the listener with location manager
		locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000,10,locationListener);
		Button tagButton = (Button)findViewById(R.id.Button4);
		tagButton.setOnClickListener(mAddListener);
		Button menu = (Button) findViewById(R.id.Button1);
		menu.setOnClickListener(menuListener);
		menuSettings = getSharedPreferences("MenuPref", MODE_PRIVATE);
		prefEditor = menuSettings.edit();
		getTagTypesFromFile();
		initMap();
		getTagsFromFile();
	}
	
	private void getTagTypesFromFile(){
		InputStream tagsFile = getBaseContext().getResources().openRawResource(R.raw.tagtypes);
		BufferedReader readTags = new BufferedReader(new InputStreamReader(tagsFile));
		try{
			String typeLine;
			while((typeLine = readTags.readLine()) != null){
				StringTokenizer parse = new StringTokenizer(typeLine,",");
				while(parse.hasMoreElements()){
					String name = parse.nextToken();
					int markerVal = Integer.parseInt(parse.nextToken(),16);
					Drawable marker = this.getResources().getDrawable(markerVal);
					marker.setBounds(-marker.getIntrinsicWidth()/2,
							-marker.getIntrinsicHeight(), marker.getIntrinsicWidth()/2, 0);
					TagType newType = new TagType(name,marker);
					tagTypes.add(newType);
					prefEditor.putBoolean(name,true);
				}
			}
			prefEditor.putInt("COLOR_CHOICE",0);
			currentType = tagTypes.get(0);
		}catch(IOException e){}
		prefEditor.commit();
	}
	
	private void getTagsFromFile(){
		InputStream tagsFile = null;
		try{
			tagsFile = openFileInput(TagFileName);
		}catch(FileNotFoundException e){
			return;
		}
		BufferedReader readTags = new BufferedReader(new InputStreamReader(tagsFile));
		try{
			String tagLine;
			while((tagLine = readTags.readLine()) != null){
				StringTokenizer parse = new StringTokenizer(tagLine,",");
				while(parse.hasMoreElements()){
					String type = parse.nextToken();
//					Log.v(ACTNAME,"type read is " + type);
					double latitude  = Double.parseDouble(parse.nextToken());// * 1000000.0;
					double longitude = Double.parseDouble(parse.nextToken());// * 1000000.0;
					Tag overlayitem = null;
					GeoPoint location = new GeoPoint((int)latitude,(int)longitude);
					TagType tagMatch = findType(type);
					if (tagMatch != null){
						overlayitem = new Tag(location,type,"");
						overlayitem.setMarker(tagMatch.getMarker());
						overlayitem.setType(tagMatch);
					}
					if (overlayitem != null){
						addOverlayItem(overlayitem);
					}
				}
			}
		}catch(IOException e){}
	}
	
	private TagType findType(String type){
//		Log.v(ACTNAME,"Searching for tag typed named " + type);
		for (TagType tagMatch : tagTypes){
//			Log.v(ACTNAME,"checking against tag type named " + tagMatch.getName());
			if (type.equals(tagMatch.getName())){
				return tagMatch;
			}
		}
		return null;
	}
	
	//Tag button anonymous classes
	private OnClickListener mAddListener = new OnClickListener(){
		public void onClick(View v){
			Tag tag = new Tag(currentLocationPoint,currentType.getName(),"");
			tag.setType(currentType);
			tag.setMarker(currentType.getMarker());
			addOverlayItem(tag);
			WriteToFile(tag);
		}
	};
	
	private void WriteToFile(Tag tag){
		try{
			FileOutputStream writer = openFileOutput(TagFileName,Context.MODE_APPEND);
			Log.v(ACTNAME,getFilesDir().toString());
			//BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(f));
//			writer.write(ACTNAME.getBytes());
			Log.v(ACTNAME,"tag info: " + tag.getInfoString());
			writer.write(tag.getInfoString().getBytes());
			writer.close();		
		}catch(Exception e){
			Log.v(ACTNAME,"Exception caught in writing to tagFile");
		} //the method is supposed to create the file, there should be no exception
	}
	
	private OnClickListener menuListener = new OnClickListener(){
		public void onClick(View view) {
			Intent myIntent = new Intent(view.getContext(), MenuActivity.class);
			startActivityForResult(myIntent, 0);
		}

	};
	protected void onResume(){
		super.onResume();
//		myLocationOverlay.enableMyLocation();
	}
	protected void onPause(){
		super.onPause();
		myLocationOverlay.disableMyLocation();
		myLocationOverlay.disableCompass();
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent data) {
		// 		int filterSeed = randGen.nextInt()+1;
		if (resultCode == RESULT_OK) {
			if (menuSettings.getInt("GPS",1) == 0){
				locationManager.removeUpdates(locationListener);
			}else{
				locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
				myLocationOverlay.enableMyLocation();
				myLocationOverlay.enableCompass();
			}
			
			for (TagType type : tagTypes){
				Log.v(ACTNAME,Boolean.toString(menuSettings.getBoolean(type.getName(),true)));
				if (menuSettings.getBoolean(type.getName(),true)){
					mapItem.filterInType(type);
				}
				else{
					mapItem.filterOutType(type);
				}
			}
			
			//until Menu_Activity is fixed
			int tagTypeNum = menuSettings.getInt("COLOR_CHOICE",0);
			currentType = tagTypes.get(tagTypeNum);
			mapItem.filterList();
			mapView.invalidate();
		}
	}
	private void addOverlayItem(Tag item){
		mapItem.addOverlay(item);
		//mapOverlays.add(mapItem);
		mapView.invalidate();
	}
	@Override
	protected boolean isRouteDisplayed() {
		// TODO Auto-generated method stub
		return false;
	}
	//
	private void initMap(){
		mapView = (MapView) findViewById(R.id.GMap);	
		mapControl = mapView.getController();
		mapView.setBuiltInZoomControls(true);
		mapControl.setZoom(18);
		currentLocationPoint = new GeoPoint(33235600,-87511691);
		//      overlayitem = new OverlayItem(currentLocationPoint, "", "");
		mapItem = new MapItem(currentType.getMarker(), this);
		//      mapItem.addOverlay(overlayitem);
		mapOverlays = mapView.getOverlays();
		mapOverlays.add(mapItem);
		//      mapOverlays.add(mapItem);
		myLocationOverlay = new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(myLocationOverlay);
		mapView.invalidate();
	}
	private class myLocationListener implements LocationListener 
	{
		@Override
		public void onLocationChanged(Location loc) {
			if (loc != null) {
				//Geopoints in microdegrees latitude or longitude times 10^6
				currentLocationPoint = new GeoPoint((int)(loc.getLatitude() * 1000000.0), (int)(loc.getLongitude()*1000000.0));
				Toast.makeText(getBaseContext(), 
						"Location changed : Latitude: " + loc.getLatitude() + 
						" Longitude: " + loc.getLongitude(), 
						Toast.LENGTH_SHORT).show();
				mapControl.setCenter(currentLocationPoint); //should be removed for actual app use.  Maybe?
			}
		}
		@Override
		public void onProviderDisabled(String provider) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onProviderEnabled(String provider) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub
		}
	}    

}
